package com.jp.knowledge.my.base;

import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jp.knowledge.util.ImageLoadUtil;

/**
 * RecycleView ItemViewHolder
 *
 * @author gzejia 978862664@qq.com
 */
public class RecycleVHolder extends RecyclerView.ViewHolder {

    private SparseArray<View> viewHolder;
    private View view;

    public RecycleVHolder(View itemView) {
        super(itemView);
        this.view = itemView;
        viewHolder = new SparseArray<>();
        view.setTag(viewHolder);
    }

    public static RecycleVHolder getViewHolder(View view) {
        RecycleVHolder viewHolder = (RecycleVHolder) view.getTag();
        if (null == viewHolder) {
            viewHolder = new RecycleVHolder(view);
            view.setTag(viewHolder);
        }
        return viewHolder;
    }

    public <T extends View> T get(int id) {
        View childView = viewHolder.get(id);
        if (null == childView) {
            childView = view.findViewById(id);
            viewHolder.put(id, childView);
        }
        return (T) childView;
    }

    public View getConvertView() {
        return view;
    }

    public TextView getTextView(int id) {
        return get(id);
    }

    public Button getButton(int id) {
        return get(id);
    }

    public ImageView getImageView(int id) {
        return get(id);
    }

    public void setTextView(int id, CharSequence charSequence) {
        getTextView(id).setText(charSequence);
    }

    public void setImageResource(int id, int resId) {
        getImageView(id).setImageResource(resId);
    }

    public void setImageUrl(int id, String url){
        ImageView imageView = getImageView(id);
        ImageLoadUtil.load(imageView.getContext(), url,imageView);
    }

    public void setVisibility(int id, boolean isVisibility) {
        get(id).setVisibility(isVisibility ? View.VISIBLE : View.GONE);
    }
}